package com.juhuixing.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName HttpUtils
 * @Description TODO
 * @Author 刘猛
 * @Date 2019/4/30 13:42
 **/
public class IMHttpUtils {
    private static final String encode = "utf-8";
    /**
     * 功能描述: IM post请求
     * @methodName postForJSONObject
     * @author: 刘猛
     * @date: 2019/4/30 13:56
     * @param: [url, postData, token]
     * @return: com.alibaba.fastjson.JSONObject
     **/
    public static JSONObject postForJSONObject(String url,JSONObject postData,String token){
        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        if(Objects.nonNull(postData)){
            StringEntity postingString = new StringEntity(postData.toJSONString(),encode);
            post.setEntity(postingString);
        }
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Bearer " + token);
        HttpResponse response = null;
        JSONObject result = null;
        try {
            response = httpClient.execute(post);
            result = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
       return result;
    }

    /**
     * 功能描述: IM get请求
     * @methodName getForJSONObject
     * @author: 刘猛
     * @date: 2019/4/30 13:56
     * @param: [url, getData, token]
     * @return: com.alibaba.fastjson.JSONObject
     **/
    public static JSONObject getForJSONObject(String url,JSONObject getData,String token){
        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        List<NameValuePair> params = new ArrayList<>();
        if(Objects.nonNull(getData)){
            getData.keySet().stream().forEach((key) ->{
                params.add( new BasicNameValuePair( key, getData.getString(key) ) );
            });
        }
        URI uri = null;
        try {
            uri = new URI( url + "?" + URLEncodedUtils.format( params, encode));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        HttpUriRequest request = new HttpGet(uri);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Authorization", "Bearer " + token);
        CloseableHttpResponse response = null;
        String content = null;
        try {
            response = httpClient.execute(request);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            httpClient.close();  //关闭连接、释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(content);
    }

    /**
     * 发送 http put 请求，参数以原生字符串进行提交
     * @param url
     * @return
     */
    public static JSONObject putForJSONObject(String url,JSONObject putData,String token){
        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        HttpPut httpput = new HttpPut(url);
        //设置header
        httpput.setHeader("Content-type", "application/json");
        httpput.setHeader("Authorization", "Bearer " + token);
        //组织请求参数
        if(Objects.nonNull(putData)){
            StringEntity stringEntity = new StringEntity(putData.toJSONString(), encode);
            httpput.setEntity(stringEntity);
        }
        JSONObject result = null;
        try {
            result = getJsonObject(httpClient, httpClient.execute(httpput));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JSONObject deleteForJSONObject(String url,JSONObject deleteData,String token){
        String content = null;
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpDelete httpdelete = new HttpDelete(url);
        //设置header
        httpdelete.setHeader("Content-type", "application/json");
        httpdelete.setHeader("Authorization", "Bearer " + token);
        JSONObject result = null;
        try {
            result = getJsonObject(closeableHttpClient, closeableHttpClient.execute(httpdelete));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static JSONObject getJsonObject(CloseableHttpClient closeableHttpClient, CloseableHttpResponse httpResponse) {
        String content = null;
        try {
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {   //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  JSONObject.parseObject(content);
    }
}
